import java.util.*;

public class Players {


    private final SortedMap<Integer, Collection<Player>> ageToPlayer;
    private final HashMap<String, Player> nameToPlayer;
    private final HashMap<String, Collection<Player>> teamToPlayer;

    public Players(Collection<Player> players) {
        ageToPlayer = new TreeMap<Integer, Collection<Player>>();
        nameToPlayer = new HashMap<String, Player>();
        teamToPlayer = new HashMap<String, Collection<Player>>();
        for (Player player : players) {
            if(!ageToPlayer.containsKey(player.getAge())){
                Collection<Player> playerList = new ArrayList<Player>();
                playerList.add(player);
                ageToPlayer.put(player.getAge(), playerList);
            }
            else {
                ageToPlayer.get(player.getAge()).add(player);
            }

            nameToPlayer.put(player.getName(), player);

            if(!teamToPlayer.containsKey(player.getTeam())){
                Collection<Player> playerList = new ArrayList<Player>();
                playerList.add(player);
                teamToPlayer.put(player.getTeam(), playerList);
            }
            else{
                teamToPlayer.get(player.getTeam()).add(player);
            }

        }

    }

    public Collection<Player> getPlayersOlderThan(int age) {
        Collection<Player> playersOver = new ArrayList<Player>();
        SortedMap<Integer, Collection<Player>> integerPlayerSortedMap = ageToPlayer.tailMap(age+1);
        for (Collection<Player> player : integerPlayerSortedMap.values()) {
            playersOver.addAll(player);
        }
        return playersOver;

    }

    public Player getPlayerByName(String playerName) {
        return nameToPlayer.get(playerName);
    }

    public Collection<Player> getPlayersByTeam(String team) {
        return teamToPlayer.get(team);
    }

    public void tradePlayer(Player player, String newTeamName) {
        teamToPlayer.get(player.getTeam()).remove(player);
        player.setTeam(newTeamName);
        teamToPlayer.get(newTeamName).add(player);
    }
}
